package com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkZw

import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioTracker
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragment
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.EvalBody
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.QuesMarkDeatil
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.StuAnswerMark
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.SubjectData
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter.MyVpFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter.SubjectAdapter
import com.lancoo.znbkxx.teacher.help.KeyboardStateObserverHelp
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils.returnImageUrlsFromHtml
import com.lancoo.znbkxx.teacher.widget.KWebView
import kotlinx.android.synthetic.main.aibk_fragment_mark_model_splitlayout.view.*
import kotlinx.android.synthetic.main.aibk_include_article_view.view.*
import kotlinx.android.synthetic.main.aibk_include_loading_refresh.view.*
import kotlinx.android.synthetic.main.aibk_include_mark_view.*
import kotlinx.android.synthetic.main.aibk_include_parent_audioplayer_a.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_answer_view.view.*
import kotlinx.android.synthetic.main.aibk_include_ques_web_ask_view.view.*
import kotlinx.android.synthetic.main.aibk_include_question_information_view.view.*
import java.util.*

class MarkFragmentZw(
        val indexA: Int,
        val indexB: Int,
        val activity: AibkQuesMarkActivity,
        val quesId: String,
        val startIndex: String
) : KBaseFragment() {

    private var rootView: View? = null
    private lateinit var quesMarkDeatil: QuesMarkDeatil
    private var isAddView = false
    private var fragmentList: MutableList<Fragment>? = ArrayList()
    private var itemList: ArrayList<SubjectData> = ArrayList()
    private lateinit var subjectAdapter: SubjectAdapter
    private var lastPosition = 0

    override fun createLayout(): Int {
        return R.layout.aibk_fragment_mark_model_splitlayout
    }

    override fun initView(view: View?) {
        rootView = view
        rootView!!.RlGifLoading.visibility = View.VISIBLE
        rootView!!.RlAudioPlayer.visibility = View.GONE
        rootView!!.RlArticleView.visibility = View.GONE
        audioTracker = AudioTracker()
        audioTracker!!.createAudioTrack()
        adjustPan()
    }

    //调整布局高度
    private fun adjustPan() {
        val screenHeight = DensityUtils.getScreenHeight(getActivity())
        rootView!!.sp_layout.setmSplitHeight(screenHeight * 2 / 5)
        KeyboardStateObserverHelp.getKeyboardStateObserver(getActivity()).setKeyboardVisibilityListener(object : KeyboardStateObserverHelp.OnKeyboardVisibilityListener {
            override fun onKeyboardShow() {
                rootView!!.sp_layout.setmSplitHeight(300)
            }

            override fun onKeyboardHide() {
                rootView!!.sp_layout.requestFocus()
                rootView!!.sp_layout.setmSplitHeight(screenHeight * 2 / 5)
            }
        })
    }

    private fun initSubjectAdapter() {
        setSubjectData()
        itemList[0].isSelect = true
        subjectAdapter = SubjectAdapter(activity, itemList)
        subjectAdapter.setOnItemClickListener(object : SubjectAdapter.OnItemClickListener {
            override fun onItemClickPlay(position: Int, view: View?) {
                VpAnswer.setCurrentItem(position, true)

            }
        })
        rv_subject.layoutManager = GridLayoutManager(context, 5)
        rv_subject.adapter = subjectAdapter
    }

    private fun setSubjectData() {
        itemList.clear()
        for (i in quesMarkDeatil!!.QuesDetail.ChildList.indices) {
            if (quesMarkDeatil!!.QuesDetail.ChildList[i].SortIndexType == 0) {
                var item = SubjectData()
                item.childIndex = quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList[0].SortIndex
                itemList.add(item)
            } else {
                for (j in quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList.indices) {
                    var item = SubjectData()
                    item.childIndex = quesMarkDeatil!!.QuesDetail.ChildList[i].ItemList[j].SortIndex
                    itemList.add(item)
                }
            }
        }
    }

    private fun showQuestionView() {
        //是否显示来源
        var resource = quesMarkDeatil.QuesDetail.Resource
        if (resource.isEmpty()) {
            rootView!!.IncludeQuesInformationView.visibility = View.GONE
        } else {
            rootView!!.IncludeQuesInformationView.visibility = View.VISIBLE
            rootView!!.IncludeQuesInformationView.TvSourceFrom.text = "来源: $resource"
            //隐藏试题准确率
            rootView!!.IncludeQuesInformationView.TvScoreRate.visibility = View.GONE
        }

        //加载题干内容
        val genreID = quesMarkDeatil.QuesDetail.GenreID
        var quesBody = quesMarkDeatil.QuesDetail.QuesBody
        if(genreID == 35){
            val paperZwIntroduction = resources.getString(R.string.paper_zw_introduction)
            quesBody = "<b>$paperZwIntroduction</b><br>$quesBody"
        }
        var ask = "<p style=\"word-break:break-all\">" + quesBody + "</p>"
        if (quesMarkDeatil.QuesDetail.TypeNo == "H") {
            quesMarkDeatil.QuesDetail.ChildList.forEach {
                if (it.ChildSectionName.isNotEmpty()) {
                    ask = ask + "<p style=\"word-break:break-all\">" + it.ChildSectionName
                    if (it.ChildDisplay.isNotEmpty()) {
                        ask = ask + "</br>" + it.ChildDisplay
                    }
                    ask = "$ask</p>"
                }
                ask = ask + it.ChildAsk + "</br>"
            }
            ask += getItemAnalysisAndAnswer()
        } else {
            ask = quesMarkDeatil.QuesDetail.ChildList[0].ChildAsk
            ask += getItemAnalysisAndAnswer()
        }
        ask = ask.replace("—".toRegex(), "_")
        ask = ask.replace("______________________".toRegex(), "_")
        WebStyleUtils.showWebViewCssStyle(getActivity(), rootView!!.WvAsk, ask, false)
        rootView!!.WvAsk.addJavascriptInterface(
                JSInterface(activity, returnImageUrlsFromHtml(ask)), "Android"
        )
        rootView!!.WvAsk.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                rootView!!.RlWebLoading.visibility = View.GONE
                WebStyleUtils.setWebImageClick(view, "Android")
            }
        }

        rootView!!.WvAsk.setOnScrollChangeListener(object : KWebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达地端")
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "已经到达顶端")
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
                Log.e("KWvA", "=======oldt========$oldt")
            }
        })
        initAnswerAdapter()
    }

    private fun initAnswerAdapter() {
        //加载作答区域
        fragmentList = ArrayList<Fragment>()
        fragmentList!!.clear()

        resetStuAnswer()
        val mAdapter = MyVpFragmentPagerAdapter(childFragmentManager, fragmentList as ArrayList<Fragment>)
        rootView!!.VpAnswer.adapter = mAdapter
        rootView!!.VpAnswer.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                itemList[lastPosition].isSelect = false
                itemList[lastPosition].isShowMark = false
                itemList[position].isSelect = true
                //当前显示
                setStuAnswer(lastPosition)
                //用于保存评阅
                doEvalJob(lastPosition)
                resetStuAnswer()
                subjectAdapter.notifyDataSetChanged()
                VpAnswer.adapter?.notifyDataSetChanged()
                lastPosition = position
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun resetStuAnswer() {
        var ChildListSize = quesMarkDeatil.QuesDetail.ChildList.size
        for (i in 0 until ChildListSize) {
            if (quesMarkDeatil.QuesDetail.ChildList[i].SortIndexType == 0) {
                (fragmentList as ArrayList<Fragment>)
                        .add(MarkFragmentZwParentView(activity, audioTracker, quesMarkDeatil.StuAnswerList!!, i, i))
                setShowMark(quesMarkDeatil.StuAnswerList!!)
            } else {
                for (j in quesMarkDeatil.QuesDetail.ChildList[i].ItemList.indices) {
                    (fragmentList as ArrayList<Fragment>)
                            .add(MarkFragmentZwParentView(activity, audioTracker, quesMarkDeatil.StuAnswerList!!, i, j))
                    setShowMark(quesMarkDeatil.StuAnswerList!!)
                }
            }
        }
    }

    //JS点击事件处理
    inner class JSInterface(val context: Context, var imageUrls: Array<String>?) {
        @JavascriptInterface
        fun clickFunction(position: String) {
            return
        }

        //java回调js代码，不要忘了@JavascriptInterface这个注解，不然点击事件不起作用
        @JavascriptInterface
        fun openImage(img: String, pos: Int) {
            val paths = ArrayList<String>()
            paths.add(img)
            Log.e("openImage", "$pos========点击了图片=========$img")
            ShowDialogTools.showBigImageDialog(activity, img)
        }
    }

    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        if (!isAddView && menuVisible) {
            Handler().postDelayed({
                val parentActivity: AibkQuesMarkActivity? =
                        getActivity() as AibkQuesMarkActivity?
                parentActivity?.getSingQuesMarkDetail(quesId, startIndex)
                parentActivity?.setDetailListener(object : AibkQuesMarkActivity.OnDetailListener {
                    override fun getQuesDetailSuccess(quesMarkDeatilX: QuesMarkDeatil) {
                        quesMarkDeatil = quesMarkDeatilX
                        isAddView = true
                        rootView!!.RlGifLoading.visibility = View.GONE
                        initSubjectAdapter()
                        showQuestionView()
                        //维护evalData
                        setEvalData(parentActivity)
                    }

                    override fun getQuesDetailFaile() {

                    }
                })
            }, 500)
        }
    }

    private fun setEvalData(parentActivity: AibkQuesMarkActivity) {
        val quesEntity = EvalBody.QuesListEntity(quesMarkDeatil!!)
        quesEntity.stuAnswerList?.addAll(quesMarkDeatil!!.StuAnswerList as MutableList)
        parentActivity.evalBody.quesList.add(quesEntity)
    }

    private fun getItemAnalysisAndAnswer(): String {
        var index = 0
        var itemAnalysisAndAnswer = ""
        quesMarkDeatil!!.QuesDetail.ChildList.forEach {
            index++
            var childAnalysis = it.ChildAnalysis
            if (childAnalysis.isNullOrEmpty()) {
                childAnalysis = "...略"
            }
            itemAnalysisAndAnswer = itemAnalysisAndAnswer + "<p style=\"color:#00b30d;word-break:break-all\">$index. 【参考答案】</p>" + it.ChildAnswer + "</br>" +
                    "<p style=\"color:#00afff;word-break:break-all\">【答案解析】</p>" + childAnalysis + "</br>"
        }
        return itemAnalysisAndAnswer
    }


    private fun getHtmlItemAnswer(): String {
        var itemAnswer = ""
        quesMarkDeatil!!.QuesDetail.ChildList.forEach {
            itemAnswer = itemAnswer + "<p style=\"word-break:break-all\">" + it.ItemList[0].ItemAnswer + "</p>"
        }
        val itemAnalysisAll = "<p style=\"width:100;float: left;color:#00b30d;word-break:break-all\">【参考答案】</p>$itemAnswer"
        return itemAnalysisAll
    }

    private fun getHtmlItemAnalysis(): String {
        var itemAnalysis = ""
        quesMarkDeatil!!.QuesDetail.ChildList.forEach {
            itemAnalysis = itemAnalysis + "<p style=\"word-break:break-all\">" + it.ItemList[0].ItemAnalysis + "</p>"
        }
        if (itemAnalysis.isEmpty()) {
            itemAnalysis = activity.getString(R.string.aibk_no_analyze) //...略
        }
        val itemAnalysisAll = "<p style=\"width:100;float: left;color:#00afff;word-break:break-all\">【答案解析】</p>$itemAnalysis"
        return itemAnalysisAll
    }

    //初始化小红点
    private fun setShowMark(stuAnswerList: MutableList<StuAnswerMark>) {
        //遍历所有学生，获取到每个学生的相同答题点的答案
        for (i in stuAnswerList.indices) {
            for (j in stuAnswerList[i].ChildAnswerList.indices) {
                if (stuAnswerList[i].ChildAnswerList[j].SortIndexType == 0) {
                    if (stuAnswerList[i].ChildAnswerList[j].State == 0 || stuAnswerList[i].ChildAnswerList[j].State == 1) {
                        itemList[j].isShowMark = true
                    }
                } else {
                    for (z in stuAnswerList[i].ChildAnswerList[j].ItemList.indices) {
                        if (stuAnswerList[i].ChildAnswerList[j].ItemList[z].State == 0 || stuAnswerList[i].ChildAnswerList[j].ItemList[z].State == 1) {
                            itemList[z].isShowMark = true
                        }
                    }
                }
            }
        }
    }

    //查看过后，当前列表的所有学生作答的state设置为2,小红点消失
    //全部评阅完成，小红点消失
    //遍历Parent.evalData 里面保存的State
    // quesMarkDeatil.StuAnswerList 里面的未评阅的State也要修改, 对应的isShowMark 也要修改
    private fun doEvalJob(position: Int) {
        //遍历所有试题
        for (i in activity.evalBody.quesList.indices) {
            //遍历第i个试题所有学生的作答
            for (j in activity.evalBody.quesList[i].stuAnswerList!!.indices) {
                //找到当前界面的quesId
                val stuAnswer = activity.evalBody.quesList[i].stuAnswerList!![j]
                if (stuAnswer.QuesID == quesMarkDeatil?.StuAnswerList?.get(0)!!.QuesID) {
                    //找到对应的答题点State 赋值
                    //sortIndex Type == 0
                    for (z in stuAnswer.ChildAnswerList.indices) {
                        if (stuAnswer.ChildAnswerList[z].ChildIndex == (position + 1)) {
                            if (stuAnswer.ChildAnswerList[z].SortIndexType == 0) {
                                if (stuAnswer.ChildAnswerList[z].State != 3)
                                    stuAnswer.ChildAnswerList[z].State = 2
                                for (t in stuAnswer.ChildAnswerList[z].ItemList.indices) {
                                    if (stuAnswer.ChildAnswerList[z].ItemList[t].State != 3)
                                        stuAnswer.ChildAnswerList[z].ItemList[t].State = 2
                                    activity.mTypeList!![indexA].QuesList[indexB].SortIndexList[z].IsEval = true

                                }
                            } else {
                                //sortIndexType == 1
                                for (t in stuAnswer.ChildAnswerList[z].ItemList.indices) {
                                    if (stuAnswer.ChildAnswerList[z].ItemList[t].State != 3)
                                        stuAnswer.ChildAnswerList[z].ItemList[t].State = 2
                                    activity.mTypeList!![indexA].QuesList[indexB].SortIndexList[z].IsEval = true
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun setStuAnswer(position: Int) {
        //遍历所有学生
        for (i in quesMarkDeatil.StuAnswerList!!.indices) {
            //遍历第i个学生的答题点,根据sortIndexType 决定给值
            for (j in quesMarkDeatil.StuAnswerList!![i].ChildAnswerList.indices) {
                if (quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[j].SortIndexType == 0) {
                    if (quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[position].State != 3)
                        quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[position].State = 2
                    for (z in quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[position].ItemList.indices) {
                        if (quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[position].ItemList[z].State != 3)
                            quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[position].ItemList[z].State = 2
                    }
                } else {
                    for (z in quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[j].ItemList.indices) {

                        if (quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[j].ItemList[position].State != 3) {
                            quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[j].ItemList[position].State = 2
                            quesMarkDeatil.StuAnswerList!![i].ChildAnswerList[j].State = 2
                        }
                    }
                }
            }
        }
    }

    public fun scrollToPosition(position: Int) {
        VpAnswer.setCurrentItem(position, true)
    }
}